'use strict';
const crypto = require('crypto');
const axios = require('axios');
const util = require('util');

// === 关键配置参数 ===
const CONFIG = {
  QUERY_WINDOW: 90000,     // 90秒查询窗口
  PLATFORM_DELAY: 10000,   // 10秒平台延迟
  MAX_RETRY: 2,            // 最大重试次数
  DATA_INTERVAL: 60000,    // 设备数据上报间隔(60秒)
  
  // === 设备配置 ===
  DEVICE_CONFIG: {
    productKey: 'k25es2SPWFj', 
    deviceName: 'device1',
    properties: [
      { identifier: 'LightLux', type: 'int', range: [0, 4095] },
      { identifier: 'Humidity', type: 'float', range: [0, 100] },
      { identifier: 'soilHumidity', type: 'int', range: [0, 4095], convertToPercent: true },
      { identifier: 'temperature', type: 'float', range: [-40, 80] }
    ]
  }
};

// === 密钥配置 ===
const ACCESS_KEY_ID = 'LTAI5tHEAG3GCHuV1gzoSzge';
const ACCESS_KEY_SECRET = 'fv6cpr8EyjVnsUMWFLmZYXbcBfgVCq';

// RFC3986标准URL编码 (修复版)
const specialUrlEncode = (str) => {
  return encodeURIComponent(str)
    .replace(/!/g, '%21')
    .replace(/'/g, '%27')
    .replace(/$/g, '%28')   // 修复1: 正确编码左括号
    .replace(/$/g, '%29')  // 修复2: 正确编码右括号
    .replace(/\*/g, '%2A');
};

// 确保兼容Node.js环境
const ensureTextEncoding = () => {
  if (typeof global.TextDecoder === 'undefined') {
    try {
      global.TextDecoder = util.TextDecoder;
      global.TextEncoder = util.TextEncoder;
    } catch (e) {
      console.warn('TextDecoder/TextEncoder不可用:', e.message);
    }
  }
};

ensureTextEncoding();

/**
 * 数值转换与验证 (修复版)
 */
const convertAndValidateValue = (rawValue, prop) => {
  try {
    let numValue;
    
    // 特殊处理：土壤湿度转换
    if (prop.identifier === 'soilHumidity' && prop.convertToPercent) {
      // 修复：确保数值在有效范围内再转换
      const rawNum = typeof rawValue === 'string' ? 
        parseInt(rawValue.replace('%', '').replace('!', '')) : 
        parseInt(rawValue);
      
      if (isNaN(rawNum)) return null;
      
      // 使用设备属性定义的范围
      const [min, max] = prop.range;
      numValue = Math.round(((rawNum - min) / (max - min)) * 100);
      
      // 确保在0-100范围内
      numValue = Math.max(0, Math.min(100, numValue));
    } else {
      // 通用处理
      numValue = typeof rawValue === 'string' ? 
        parseFloat(rawValue.replace('%', '').replace('!', '')) : 
        parseFloat(rawValue);
    }
    
    // 数值范围验证
    if (prop.range && (numValue < prop.range[0] || numValue > prop.range[1])) {
      console.warn(`数值超出范围: ${prop.identifier}=${numValue}`);
      return null;
    }
    
    return isNaN(numValue) ? null : numValue;
  } catch (error) {
    console.error(`数值转换错误(${prop.identifier}):`, error);
    return null;
  }
};

/**
 * 创建阿里云签名 (终极修复版)
 */
const createAliyunSignature = (params, secret) => {
  // 1. 参数排序（阿里云要求）
  const sortedKeys = Object.keys(params).sort();
  
  // 2. 构建规范化的查询字符串
  const canonicalizedQueryString = sortedKeys
    .map(key => `${specialUrlEncode(key)}=${specialUrlEncode(params[key])}`)
    .join('&');
  
  // 3. 构造待签名字符串 (阿里云标准格式)
  const stringToSign = `GET&${specialUrlEncode('/')}&${specialUrlEncode(canonicalizedQueryString)}`;
  
  console.log(`字符串待签名(StringToSign): ${stringToSign}`);
  
  // 4. 计算签名
  const signKey = `${secret}&`;
  return crypto.createHmac('sha1', signKey)
    .update(stringToSign)
    .digest('base64');
};

// 云函数入口
exports.main = async (event, context) => {
  const startTime = Date.now();
  
  const result = {
    code: 200,
    message: 'success',
    data: {},
    timestamps: {},
    meta: {
      startTime: new Date(startTime).toISOString(),
      retries: 0
    }
  };

  try {
    console.log(`==== 开始执行云函数 [${new Date().toISOString()}] ====`);
    
    // 计算时间范围 (考虑设备上报频率)
    const now = Date.now();
    const endTime = now - CONFIG.PLATFORM_DELAY;
    const startTimeQuery = endTime - CONFIG.DATA_INTERVAL * 1.5; // 考虑数据延迟
    
    // 转换为秒级时间戳
    const startTimeQuerySeconds = Math.floor(startTimeQuery / 1000);
    const endTimeSeconds = Math.floor(endTime / 1000);
    
    console.log('优化的查询时间范围(UTC):', {
      start: new Date(startTimeQuery).toISOString(),
      end: new Date(endTime).toISOString(),
      start_seconds: startTimeQuerySeconds,
      end_seconds: endTimeSeconds,
      duration: `${(endTime - startTimeQuery)/1000}秒`
    });

    // 并行查询所有属性
    const queries = CONFIG.DEVICE_CONFIG.properties.map(async (prop) => {
      let retryCount = 0;
      
      while (retryCount <= CONFIG.MAX_RETRY) {
        try {
          console.log(`查询属性: ${prop.identifier}`);
          
          // 请求参数 (阿里云要求格式)
          const requestParams = {
            Action: 'QueryDevicePropertyData',
            Format: 'JSON',
            Version: '2018-01-20',
            AccessKeyId: ACCESS_KEY_ID,
            Timestamp: new Date().toISOString().replace(/\.\d+Z/, 'Z'),
            SignatureMethod: 'HMAC-SHA1',
            SignatureVersion: '1.0',
            SignatureNonce: Math.random().toString(36).substring(2, 12),
            RegionId: 'cn-shanghai',
            ProductKey: CONFIG.DEVICE_CONFIG.productKey,
            DeviceName: CONFIG.DEVICE_CONFIG.deviceName,
            Identifier: prop.identifier,
            StartTime: startTimeQuerySeconds,
            EndTime: endTimeSeconds,
            Asc: '0',     // 0表示按时间倒序
            PageSize: '10', // 增加获取的数据量
            IotInstanceId: 'public'
          };
          
          // 计算签名
          const signature = createAliyunSignature(requestParams, ACCESS_KEY_SECRET);
          
          // 将签名加入参数
          const signedParams = {
            ...requestParams,
            Signature: signature
          };
          
          // 构建URL查询字符串
          const queryString = Object.keys(signedParams)
            .sort() // 阿里云要求参数排序
            .map(key => `${key}=${encodeURIComponent(signedParams[key])}`)
            .join('&');
          
          const url = `https://iot.cn-shanghai.aliyuncs.com/?${queryString}`;
          console.log(`属性 ${prop.identifier} 请求URL: ${url}`);
          
          // 发送请求
          const response = await axios.get(url, {
            timeout: 10000,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
            }
          });
          
          // 处理响应
          if (response.data && response.data.Success) {
            const records = response.data.Data?.List?.PropertyInfo || [];
            console.log(`属性 ${prop.identifier} 获取记录数: ${records.length}`);
            
            // 查找最新有效值
            let validRecord = null;
            for (let record of records) {
              const value = convertAndValidateValue(record.Value, prop);
              if (value !== null) {
                validRecord = {
                  value,
                  timestamp: record.Time * 1000 // 转换为毫秒
                };
                break; // 取最新有效值
              }
            }
            
            if (validRecord) {
              console.log(`属性 ${prop.identifier} 找到有效值: ${validRecord.value}`);
              return {
                identifier: prop.identifier,
                value: validRecord.value,
                timestamp: validRecord.timestamp
              };
            }
            
            console.warn(`无有效记录: ${prop.identifier}`);
            return null;
          } else {
            const errorMsg = response.data?.Message || '未知API错误';
            const errorCode = response.data?.Code || 'UNKNOWN_ERROR';
            
            console.error(`API错误详情: ${errorCode} - ${errorMsg}`);
            throw new Error(`API响应错误: ${errorMsg} (Code: ${errorCode})`);
          }
        } catch (error) {
          if (retryCount < CONFIG.MAX_RETRY) {
            retryCount++;
            result.meta.retries++;
            console.warn(`请求失败重试(${prop.identifier}): 第${retryCount}次`);
            await new Promise(resolve => setTimeout(resolve, 300));
            continue;
          }
          
          const errorMessage = error.response?.data?.Message || error.message;
          const errorCode = error.response?.data?.Code || 'UNKNOWN_ERROR';
          
          console.error(`查询属性失败(${prop.identifier}): ${errorCode} - ${errorMessage}`);
          return {
            identifier: prop.identifier,
            error: errorMessage,
            code: errorCode
          };
        }
      }
    });
    
    // 等待所有查询完成
    const results = await Promise.all(queries);
    
    // 处理结果
    let validDataCount = 0;
    results.forEach(item => {
      if (item && item.value !== null && !item.error) {
        result.data[item.identifier] = item.value;
        result.timestamps[item.identifier] = item.timestamp;
        validDataCount++;
      } else if (item?.error) {
        if (!result.errors) result.errors = {};
        result.errors[item.identifier] = item.error;
      }
    });
    
    // 设置最终状态
    if (validDataCount === 0) {
      result.code = 503;
      result.message = '未获取到有效数据';
    } else if (Object.keys(result.errors || {}).length > 0) {
      result.code = 206;
      result.message = `部分数据获取失败`;
    }

  } catch (globalError) {
    console.error('[全局错误]', globalError);
    result.code = 500;
    result.message = `服务器错误: ${globalError.message}`;
  } finally {
    // 添加执行时间
    const endTime = Date.now();
    result.meta.endTime = new Date(endTime).toISOString();
    result.meta.executionTime = `${endTime - startTime}ms`;
    console.log(`==== 结束执行云函数 (${result.meta.executionTime}) ====`);
  }
  
  return result;
};